﻿#include "all_book.h"
#include "ui_all_book.h"
#include <QSortFilterProxyModel>
all_book::all_book(QWidget *parent) :
    QWidget(parent),//testing
    ui(new Ui::all_book)
{
    this->setAttribute(Qt::WA_DeleteOnClose);
    bok =new book_sql;
    ui->setupUi(this);
    //以下部分为拷贝来的
    model = new QSqlTableModel(this,bok->book_db);//设置表
    model->setTable("book_info");
    model->select();

    model->setEditStrategy(QSqlTableModel::OnManualSubmit);

    ui->tableView->setModel(model);
    model->setTable("book_info");
    ui->search_inoput->setPlaceholderText("请输入书名或者作者进行查找");
    //设置只能单选
    ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);
    //设置选择行
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    model->select();
    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableView->resizeColumnsToContents();
    ui->tableView->resizeRowsToContents();
    ui->tableView->setAlternatingRowColors(true);
    ui->search_inoput->setText("");
    QString s= QString(ui->search_inoput->text());
    qDebug()<<"search_inoput at initial "<<s;

}

void all_book::set_table_model(QStandardItemModel *model)
{ui->tableView->setModel(model);
 ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);


}

all_book::~all_book()
{
    delete ui;
}
void all_book::book_show(void)
{
    qDebug()<<"search-showing";
}
void all_book::on_search_btn_clicked()//点击的时候出现
{
    QString s= QString(ui->search_inoput->text());
    qDebug()<<s;//这里是如果内容为空全部恢复为初始状态
    if(count==0&&s=="")
    {
        qDebug()<<" empty input "<<s;
        return;
    }
    if(s=="")
    {
        qDebug()<<"empty input "<<s;
        model->setTable("book_info");
        model->select();
        return;
    }
     QSqlQuery sql(bok->book_db);
     QString strSql = "SELECT * FROM book_info WHERE book like '%"+s+"%' or author like '%"+s+"%'";
//     QString strSql = QString("SELECT * FROM book_info WHERE book=%1").arg(s);//从书名开始搜索
     //只能进行英文搜索
     sql.exec(strSql);//成功搜索，怎么表示信息呢？

     QString str = ui->search_inoput->text();
     QString sname = "book like '%"+str+"%' or author like '%"+s+"%'";
//     QString sname = QString("book = '%1'").arg(str);//打包
     model->setFilter(sname);
     model->select();      //再次显示一次

     while(sql.next())
     {
         qDebug()<<"Found"<<sql.value(0).toString()<<sql.value(1).toString()<<sql.value(2).toString()<<
                   sql.value(3).toString()<<sql.value(4).toString()<<sql.value(5).toString()<<
                   sql.value(5).toString()<<sql.value(6).toString()<<sql.value(7).toString();

     }
    count++;
}

